package com.gui.juc.base.thread.method;

import cn.hutool.core.util.RandomUtil;
import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class JoinDemo {

    static int var = 0;

    public static void main(String[] args) throws InterruptedException {
        testJoinWithTimeOut();
    }

    private static void testJoin() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            int timeout = RandomUtil.randomInt(1, 10);
            log.debug("t1 start running, wait {}【s】", timeout);
            Sleeper.sleep(TimeUnit.SECONDS, timeout);
            var = 20;
            log.debug("t1 stop running...");
        }, "t1");
        t1.start();
        t1.join();
        log.debug("var result:{}", var);
    }

    private static void testJoinWithTimeOut() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            int timeout = RandomUtil.randomInt(1, 10);
            log.debug("t1 start running, wait {}【s】", timeout);
            Sleeper.sleep(TimeUnit.SECONDS, timeout);
            var = 20;
            log.debug("t1 stop running...");
        }, "t1");

        t1.start();
        t1.join(5000);
        log.debug("var result:{}", var);
    }
}
